package ${packageName}.api.interceptor;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.HttpUrl;

public class AuthTokenInterceptor implements Interceptor {
    private static final int CODE_REDIRECT_START = 300;
    private static final int CODE_REDIRECT_END = 307;

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request originalRequest = chain.request();

        Request requestWithUserAgent = originalRequest.newBuilder()
                .header("Connection", "Close")
                .build();

        Response originalResponse = chain.proceed(requestWithUserAgent);
        if (originalResponse.code() >= CODE_REDIRECT_START
                && originalResponse.code() <= CODE_REDIRECT_END) {
            String redirectUrl = originalResponse.header("Location");
            originalResponse.body().close();

            return chain.proceed(originalRequest.newBuilder()
                    .url(HttpUrl.parse(redirectUrl))
                    .header("Connection", "Close")
                    .build());
        }

        return originalResponse;
    }
}
